package com.seisys.controller.system.area;


import java.io.PrintWriter;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.seisys.controller.base.BaseController;
import com.seisys.entity.Page;
import com.seisys.entity.system.Area;
import com.seisys.service.system.LogService;
import com.seisys.service.system.area.AreaService;
import com.seisys.util.Const;
import com.seisys.util.Jurisdiction;
import com.seisys.util.LogUtil;
import com.seisys.util.ObjectExcelView;
import com.seisys.util.PageData;

import net.sf.json.JSONArray;


/**
 * 类名称：AreaController 创建人：FH 创建时间：2017-04-07
 */
@Controller
@RequestMapping(value = "/area")
public class AreaController extends BaseController
{

    String menuUrl = "area/list.do"; // 菜单地址(权限用)

    private static final String MODULENAME = "区域管理";

    @Resource(name = "logService")
    private LogService logService;

    @Resource(name = "areaService")
    private AreaService areaService;

    /**
     * 新增
     */
    @RequestMapping(value = "/save")
    public ModelAndView save()
        throws Exception
    {
        logBefore(logger, "新增Area");
        if (!Jurisdiction.buttonJurisdiction(menuUrl, "add"))
        {
            return null;
        } // 校验权限
        ModelAndView mv = this.getModelAndView();
        PageData pd = new PageData();
        pd = this.getPageData();
        pd.put("ID", this.get32UUID()); // 主键
        areaService.save(pd);
        LogUtil.getInstance().operationLogger(LogUtil.ADD, MODULENAME, pd.getString("ID"),
            logService, request);
        mv.addObject("msg", "success");
        mv.setViewName("save_result");
        return mv;
    }

    /**
     * 删除
     */
    @RequestMapping(value = "/delete")
    @ResponseBody
    public String delete(PrintWriter out)
    {
        logBefore(logger, "删除Area");
        if (!Jurisdiction.buttonJurisdiction(menuUrl, "del"))
        {
            return "";
        } // 校验权限
        PageData pd = new PageData();
        try
        {
            pd = this.getPageData();
            areaService.delete(pd);
            LogUtil.getInstance().operationLogger(LogUtil.DELETE, MODULENAME, pd.getString("ID"),
                logService, request);
//            out.write("success");
//            out.close();
            return "success";
        }
        catch (Exception e)
        {
            logger.error(e.toString(), e);
            return "error";
        }

    }

    /**
     * 修改
     */
    @RequestMapping(value = "/edit")
    public ModelAndView edit()
        throws Exception
    {
        logBefore(logger, "修改Area");
        if (!Jurisdiction.buttonJurisdiction(menuUrl, "edit"))
        {
            return null;
        } // 校验权限
        ModelAndView mv = this.getModelAndView();
        PageData pd = new PageData();
        pd = this.getPageData();
        areaService.edit(pd);
        LogUtil.getInstance().operationLogger(LogUtil.UPDATE, MODULENAME, pd.getString("ID"),
            logService, request);
        mv.addObject("msg", "success");
        mv.setViewName("save_result");
        return mv;
    }

    /**
     * 列表
     */
    @RequestMapping(value = "/list")
    public ModelAndView list(Page page, Model model)
    {
        logBefore(logger, "列表Area");
        // if(!Jurisdiction.buttonJurisdiction(menuUrl, "cha")){return null;}
        // //校验权限
        ModelAndView mv = this.getModelAndView();
        PageData pd = new PageData();
        try
        {
            pd = this.getPageData();
            page.setPd(pd);
            // List<PageData> varList = areaService.list(page); //列出Area列表
            mv.setViewName("system/area/area_list");
            // mv.addObject("varList", varList);
            // List<Area> list = areaService.findAllList();
            mv.addObject("pd", pd);
            mv.addObject(Const.SESSION_QX, this.getHC()); // 按钮权限
        }
        catch (Exception e)
        {
            logger.error(e.toString(), e);
        }
        return mv;
    }

    /**
     * 去新增页面
     */
    @RequestMapping(value = "/goAdd")
    public ModelAndView goAdd()
    {
        logBefore(logger, "去新增Area页面");
        ModelAndView mv = this.getModelAndView();
        PageData pd = new PageData();
        pd = this.getPageData();
        try
        {
            mv.setViewName("system/area/area_edit");
            mv.addObject("msg", "save");
            mv.addObject("pd", pd);
        }
        catch (Exception e)
        {
            logger.error(e.toString(), e);
        }
        return mv;
    }

    /**
     * 去修改页面
     */
    @RequestMapping(value = "/goEdit")
    public ModelAndView goEdit()
    {
        logBefore(logger, "去修改Area页面");
        ModelAndView mv = this.getModelAndView();
        PageData pd = new PageData();
        pd = this.getPageData();
        try
        {
            pd = areaService.findById(pd); // 根据ID读取
            String parentId = pd.getString("PARENT_ID");
            Area a = areaService.findAreaById(parentId);
            if (null == a || a.getName().equals(""))
            {
                pd.put("PARENTNAME", "");
            }
            else
            {
                pd.put("PARENTNAME", a.getName());
            }
            mv.setViewName("system/area/area_edit");
            mv.addObject("msg", "edit");
            mv.addObject("pd", pd);
        }
        catch (Exception e)
        {
            logger.error(e.toString(), e);
        }
        return mv;
    }

    /**
     * 批量删除
     */
    @RequestMapping(value = "/deleteAll")
    @ResponseBody
    public Object deleteAll()
    {
        logBefore(logger, "批量删除Area");
        if (!Jurisdiction.buttonJurisdiction(menuUrl, "dell"))
        {
            return null;
        } // 校验权限
        PageData pd = new PageData();
        Map<String, Object> map = new HashMap<String, Object>();
        try
        {
            pd = this.getPageData();
            List<PageData> pdList = new ArrayList<PageData>();
            String DATA_IDS = pd.getString("DATA_IDS");
            if (null != DATA_IDS && !"".equals(DATA_IDS))
            {
                String ArrayDATA_IDS[] = DATA_IDS.split(",");
                areaService.deleteAll(ArrayDATA_IDS);
                LogUtil.getInstance().operationLogger(LogUtil.DELETE, MODULENAME, DATA_IDS,
                    logService, request);
                pd.put("msg", "ok");
            }
            else
            {
                pd.put("msg", "no");
            }
            pdList.add(pd);
            map.put("list", pdList);
        }
        catch (Exception e)
        {
            logger.error(e.toString(), e);
        }
        finally
        {
            logAfter(logger, "");
        }
        return com.seisys.util.AppUtil.returnObject(pd, map);
    }

    /*
     * 导出到excel
     * @return
     */
    @RequestMapping(value = "/excel")
    public ModelAndView exportExcel()
    {
        logBefore(logger, "导出Area到excel");
        if (!Jurisdiction.buttonJurisdiction(menuUrl, "cha"))
        {
            return null;
        }
        ModelAndView mv = new ModelAndView();
        PageData pd = new PageData();
        pd = this.getPageData();
        try
        {
            Map<String, Object> dataMap = new HashMap<String, Object>();
            List<String> titles = new ArrayList<String>();
            titles.add("区域编码"); // 1
            titles.add("区域类型"); // 2
            titles.add("分类"); // 3
            titles.add("地区名称"); // 4
            dataMap.put("titles", titles);
            List<PageData> varOList = areaService.listAll(pd);
            List<PageData> varList = new ArrayList<PageData>();
            for (int i = 0; i < varOList.size(); i++ )
            {
                PageData vpd = new PageData();
                vpd.put("var1", varOList.get(i).getString("CODE")); // 1
                vpd.put("var2", varOList.get(i).getString("TYPE")); // 2
                vpd.put("var3", varOList.get(i).get("SORT").toString()); // 3
                vpd.put("var4", varOList.get(i).getString("NAME")); // 4
                varList.add(vpd);
            }
            dataMap.put("varList", varList);
            ObjectExcelView erv = new ObjectExcelView();
            mv = new ModelAndView(erv, dataMap);
        }
        catch (Exception e)
        {
            logger.error(e.toString(), e);
        }
        return mv;
    }

    @RequestMapping(value = "/getAreaList")
    @ResponseBody
    public Map<String, Object> getOfficeList(HttpServletRequest request,
                                             HttpServletResponse response)
        throws Exception
    {
        boolean success = true;
        String msg = "";
        Map<String, Object> result = new HashMap<String, Object>();
        try
        {
            List<Area> list = areaService.findAllList();
            result.put("areaList", list);
        }
        catch (Exception e)
        {
            success = false;
            msg = "查询错误";
        }
        result.put("success", success);
        result.put("msg", msg);
        return result;

    }

    @RequestMapping(value = "/treeData")
    @ResponseBody
    public Map<String, Object> getAreaTreeData(HttpServletRequest request,
                                               HttpServletResponse response)
        throws Exception
    {
        boolean success = true;
        String msg = "";
        String json = "";
        Map<String, Object> result = new HashMap<String, Object>();
        try
        {
            List<Area> list = areaService.listAllArea();
            JSONArray arr = JSONArray.fromObject(list);
            json = arr.toString();
            json = json.replaceAll("areaSub", "nodes");
            result.put("zTreeNodes", json);
        }
        catch (Exception e)
        {
            success = false;
            msg = "网络请求失败";
        }
        result.put("success", success);
        result.put("msg", msg);
        return result;
    }

    /* ===============================权限================================== */
    public Map<String, String> getHC()
    {
        Subject currentUser = SecurityUtils.getSubject(); // shiro管理的session
        Session session = currentUser.getSession();
        return (Map<String, String>)session.getAttribute(Const.SESSION_QX);
    }

    /* ===============================权限================================== */

    @InitBinder
    public void initBinder(WebDataBinder binder)
    {
        DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        binder.registerCustomEditor(Date.class, new CustomDateEditor(format, true));
    }
}
